package com.weixing.mall.provider.controller.rpc;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.weixing.mall.base.exception.BusinessException;
import com.weixing.mall.base.wrapper.Result;
import com.weixing.mall.base.wrapper.ResultUtil;
import com.weixing.mall.base.enums.WhetherEnum;
import com.weixing.mall.provider.api.model.dto.AfterOrderImgDto;
import com.weixing.mall.provider.api.model.dto.SeckillOrderDto;
import com.weixing.mall.provider.api.model.dto.SeckillOrderImportDto;
import com.weixing.mall.provider.api.model.enums.AgentLevelEnum;
import com.weixing.mall.provider.api.model.enums.OrderTypeEnum;
import com.weixing.mall.provider.api.model.enums.SettleStateEnum;
import com.weixing.mall.provider.api.model.vo.*;
import com.weixing.mall.provider.api.service.AgentServiceRpc;
import com.weixing.mall.provider.api.service.SysUserRpcService;
import com.weixing.mall.provider.manager.ProfitManager;
import com.weixing.mall.provider.model.domain.AfterSaleImg;
import com.weixing.mall.provider.model.domain.Order;
import com.weixing.mall.provider.model.domain.OrderAgent;
import com.weixing.mall.provider.model.domain.OrderExpress;
import com.weixing.mall.provider.model.enums.AuditDeptEnum;
import com.weixing.mall.provider.model.enums.OrderAuditStateEnum;
import com.weixing.mall.provider.model.enums.OrderFromEnum;
import com.weixing.mall.provider.model.enums.OrderStateEnum;
import com.weixing.mall.provider.model.query.AgentOrderQuery;
import com.weixing.mall.provider.model.vo.FrontAgentOrderVo;
import com.weixing.mall.provider.model.vo.OrderGoodsVo;
import com.weixing.mall.provider.service.*;
import com.weixing.mall.provider.util.OrderUtil;
import com.weixing.mall.util.ListUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author wx
 * @Date 2019/12/4 15:44
 * @Version 1.0
 */
@RestController
@RequestMapping("/api/order")
public class OrderRpcController {
    @Autowired
    private IOrderService orderService;
    @Autowired
    private IOrderGoodsService orderGoodsServiceImpl;
    @Autowired
    private IAfterSaleService afterSaleService;
    @Autowired
    private AgentServiceRpc agentServiceRpc;
    @Autowired
    private ProfitManager profitManager;
    @Autowired
    private IAgentOrderService agentOrderService;
    @Autowired
    private IOrderExpressService orderExpressService;
    @Autowired
    private SysUserRpcService sysUserRpcService;
    @Autowired
    private  IAfterSaleImgService  afterSaleImgService;

    @GetMapping("selectByAgentSn")
    public OrderTypeEnum selectByAgentSn(String orderSn) {
        return orderService.selectByAgentSn(orderSn);
    }

    @GetMapping("sealingSheetOrderList")
    List<SealingSheetOrderVo> sealingSheetOrderList() {
        List<SealingSheetOrderVo> list = orderService.sealingSheetOrderList();
        return list;
    }

    @GetMapping("getOrderGoodById")
    public OrderGoodItvmVo getOrderGoodById(Long orderId) {
        OrderGoodsVo orderGoodsVo = orderGoodsServiceImpl.findByOrderId(orderId);
        OrderGoodItvmVo itvmVo = new OrderGoodItvmVo();
        BeanUtils.copyProperties(orderGoodsVo, itvmVo);
        return itvmVo;
    }

    /**
     * 保存售后图片信息
     * @param imgDto
     * @return
     */
    @PostMapping("saveAfterOrderImg")
    public Result afterSaleImgService(@RequestBody AfterOrderImgDto imgDto) {
        try{
            List<AfterSaleImg> imgList=Lists.newArrayList();
            List<String> list=imgDto.getImg();
            for(String img:list){
                AfterSaleImg afterSaleImg=new AfterSaleImg();
                afterSaleImg.setAfterSaleId(imgDto.getAfterSaleId());
                afterSaleImg.setImg(img);
                imgList.add(afterSaleImg);
            }
            afterSaleImgService.saveBatch(imgList, ListUtil.SIZE);
        }catch (Exception e){
            return ResultUtil.error();
        }
        return ResultUtil.success();
    }

    @GetMapping("updateStatus")
    public Result updateStatus(Long id, Integer status) {
        Order order = new Order();
        order.setId(id);
        order.setOrderStatus(status);
        orderService.updateById(order);
        return ResultUtil.success();
    }

    @GetMapping("selectById")
    public Result selectById(Long id) {
        Order order = orderService.getById(id);
        if (null == order) {
            return ResultUtil.error("订单不存在");
        }
        OrderItemVo vo = new OrderItemVo();
        BeanUtils.copyProperties(order, vo);
        return ResultUtil.success(vo);
    }

    @GetMapping("getCountfrontOrder")
    public int getCountfrontOrder(Long memberId, Integer frontOrderStatus) {
        int orderNum = orderService.getCountfrontOrder(memberId, frontOrderStatus);
        return orderNum;
    }

    @GetMapping("byDepotId")
    public List<TransferListVo> byDepotId(Long depotId) {
        List<TransferListVo> list = orderService.byDepotId(depotId);
        return list;
    }

    @GetMapping("updateOrderStatus")
    public Result updateOrderStatus(Integer depotId) {
        orderService.updateStatus(depotId);
        return ResultUtil.success();
    }

    @GetMapping(value = "updateAfterSaleStatus")
    public Result updateAfterSaleStatusVal(Long id, Integer type, Long operatorId, String operatorName) {
        afterSaleService.updateAfterSaleStatusVal(id, type, null, null, null, operatorId, operatorName);
        return ResultUtil.success();
    }

    @GetMapping(value = "updateDepotInfo")
    public Result updateDepotInfo(Long id, String depotSn, String depotLocation, String depotOrder) {
        afterSaleService.updateDepotInfo(id, depotSn,depotLocation,depotOrder);
        return ResultUtil.success();
    }

    @GetMapping("selectAgentActOrdersByActId")
    public Result selectAgentActOrdersByActId(Long actId) {
        List<ActOrderSettleVo> voList = orderService.selectAgentActOrdersByActId(actId);
        return ResultUtil.success(voList);
    }


    private List<Order> getSeckillOrderImportVos(@RequestBody List<String> orderSnList) {
        QueryWrapper<Order> wrapper = new QueryWrapper<Order>().in("identification_code", orderSnList);
        List<Order> list = orderService.list(wrapper);
        return list;
    }


    private Order getSeckillOrderImportVo(String identificationCode) {
        QueryWrapper<Order> wrapper = new QueryWrapper<Order>().eq("identification_code", identificationCode);
        return orderService.getOne(wrapper);
    }


    /**
     * 方法描述: 秒杀订单导入
     *
     * @Author Small
     * @param seckillOrderDto
     * @Date 2020/6/5 9:11
     * @return com.weixing.mall.base.wrapper.Result
     */
    @PostMapping("executeSeckillOrderImport")
    public Result executeSeckillOrderImport(@RequestBody SeckillOrderDto seckillOrderDto) {

        /*
         * 先对数据进行分组，减少数据库请求此时
         * 1.先对代理商编号进行分组
         * 2.再对会员编号进行分组
         */
        List<Order> orderList = Lists.newArrayList();
        List<OrderAgent> orderAgentList = Lists.newArrayList();
        List<SeckillOrderImportDto> dtoList = seckillOrderDto.getOrderList();
        Long rebateRule = seckillOrderDto.getRebateRule();
        Long actId = seckillOrderDto.getActId();

        Map<String, List<SeckillOrderImportDto>> map = dtoList.stream().collect(Collectors.groupingBy(t -> t.getAgentMobile()));


        // 循环读取数据
        for (Map.Entry<String, List<SeckillOrderImportDto>> entry : map.entrySet()) {
            String mobile = entry.getKey();
            Result<AgentRpcVo> agentResult = agentServiceRpc.selectByAgentMobile(mobile);
            if (!agentResult.isSuccess()) {
                throw new BusinessException("代理商服务不可用");
            }
            AgentRpcVo agentVo = agentResult.getData();
            if (null == agentVo) {
                throw new BusinessException(StrUtil.format("代理商{},不存在", mobile));
            }
            List<SeckillOrderImportDto> dataList = entry.getValue();
            for (SeckillOrderImportDto dto : dataList) {
                Order order = getSeckillOrderImportVo(dto.getIdentificationCode());
                if (null == order) {
                    throw new BusinessException(StrUtil.format("订单{}，不存在", dto.getIdentificationCode()));
                }
                if (actId.longValue() != order.getActId().longValue()) {
                    throw new BusinessException(StrUtil.format("订单{}，不属于该活动", dto.getIdentificationCode()));
                }
                if (!order.getOutTradeNo().equals(dto.getOutTradeNo())) {
                    throw new BusinessException(StrUtil.format("订单{}，与交易流水号{}不匹配", dto.getIdentificationCode(), dto.getOutTradeNo()));
                }
                order.setAgentId(agentVo.getId());
                order.setAgentSn(agentVo.getAgentSn());
                order.setAgentName(agentVo.getAgentName());
                order.setAgentCliamLine(agentVo.getAgentTreePath());
                order.setCustomerId(agentVo.getCustomerId());
                order.setCustomerName(agentVo.getCustomerName());
                OrderUtil.doOrderAgentClaim(order);
                if (null != order.getDistributorId() && 0 != order.getDistributorId()) {
                    List<AgentRpcVo> treeList = agentVo.getTreeList();
                    int size = treeList.size();
                    AgentRpcVo agentRpcVo1 = treeList.get(size - 1);
                    if (AgentLevelEnum.DEALER.getValue().equals(agentRpcVo1.getAgentLevel())) {
                        order.setDistributorName(agentRpcVo1.getAgentName());
                    }
                }
                // 订单审核直接流转到客服
                order.setAuditor(agentVo.getCustomerId());
                order.setAuditDept(AuditDeptEnum.SERVICE_DEPT.getValue());
                order.setAuditStatus(OrderAuditStateEnum.AGENT_AUDIT_SUCCESS.getValue());
                order.setOrderStatus(OrderStateEnum.HAS_PAY.getValue());
                // 代理获利计算
                orderAgentList.addAll(profitManager.calcProfit(order, agentVo, rebateRule));
                // 校验是否更新收货地址
                if (StrUtil.isNotEmpty(dto.getContactUser())) {
                    if (StrUtil.isEmpty(dto.getContactPhone())
                            || StrUtil.isEmpty(dto.getProvince())
                            || StrUtil.isEmpty(dto.getCity())
                            || StrUtil.isEmpty(dto.getRegion())
                            || StrUtil.isEmpty(dto.getAddrDetail())) {
                        throw new BusinessException("请完善收货人及收货地址信息");
                    }
                    OrderExpress byOrderId = orderExpressService.findByOrderId(order.getId());
                    if (!byOrderId.getContactUser().equals(dto.getContactUser().trim())
                            || !byOrderId.getContactPhone().equals(dto.getContactPhone())
                            || !byOrderId.getProvince().equals(dto.getProvince())
                            || !byOrderId.getCity().equals(dto.getCity())
                            || !byOrderId.getRegion().equals(dto.getRegion())
                            || !byOrderId.getAddrDetail().equals(dto.getAddrDetail())) {
                        byOrderId.setContactUser(dto.getContactUser());
                        byOrderId.setContactPhone(dto.getContactPhone());
                        byOrderId.setProvince(dto.getProvince());
                        byOrderId.setCity(dto.getCity());
                        byOrderId.setRegion(dto.getRegion());
                        byOrderId.setAddrDetail(dto.getAddrDetail());
                        orderExpressService.updateById(byOrderId);
                    }
                }
                orderList.add(order);
            }

        }
        orderService.executeSeckillOrderImport(orderList, orderAgentList);
        return ResultUtil.success();
    }

    /**
     * 方法描述: 秒杀订单导入
     *
     * @Author Small
     * @param seckillOrderDto
     * @Date 2020/6/5 9:11
     * @return com.weixing.mall.base.wrapper.Result
     */
    @PostMapping("executeSeckillOrderImport4kefu")
    public Result executeSeckillOrderImport4kefu(@RequestBody SeckillOrderDto seckillOrderDto) {

        /*
         * 先对数据进行分组，减少数据库请求此时
         * 1.先对代理商编号进行分组
         * 2.再对会员编号进行分组
         */
        List<Order> orderList = Lists.newArrayList();
        List<OrderAgent> orderAgentList = Lists.newArrayList();
        List<SeckillOrderImportDto> dtoList = seckillOrderDto.getOrderList();
        Long rebateRule = seckillOrderDto.getRebateRule();
        Long actId = seckillOrderDto.getActId();

        Map<String, List<SeckillOrderImportDto>> map = dtoList.stream().collect(Collectors.groupingBy(t -> t.getAgentMobile()));


        // 循环读取数据
        for (Map.Entry<String, List<SeckillOrderImportDto>> entry : map.entrySet()) {
            String kefuLoginName = entry.getKey();
            Result<KefuVo> kefuVoResult = sysUserRpcService.loadKefuByUserName(kefuLoginName);
            if (!kefuVoResult.isSuccess()) {
                throw new BusinessException(kefuVoResult.getMsg());
            }
            KefuVo kefuVo = kefuVoResult.getData();
            if (null == kefuVo) {
                throw new BusinessException(StrUtil.format("客服{},不存在", kefuLoginName));
            }
            List<SeckillOrderImportDto> dataList = entry.getValue();
            for (SeckillOrderImportDto dto : dataList) {
                Order order = getSeckillOrderImportVo(dto.getIdentificationCode());
                if (null == order) {
                    throw new BusinessException(StrUtil.format("订单{}，不存在", dto.getIdentificationCode()));
                }
                if (actId.longValue() != order.getActId().longValue()) {
                    throw new BusinessException(StrUtil.format("订单{}，不属于该活动", dto.getIdentificationCode()));
                }
                if (!order.getOutTradeNo().equals(dto.getOutTradeNo())) {
                    throw new BusinessException(StrUtil.format("订单{}，与交易流水号{}不匹配", dto.getIdentificationCode(), dto.getOutTradeNo()));
                }
                order.setAgentId(0L);
                order.setAgentSn("");
                order.setAgentName("");
                order.setAgentCliamLine("");
                order.setCustomerId(kefuVo.getId());
                order.setCustomerName(kefuVo.getRealName());
                OrderUtil.clearOrderAgentClaim(order);
                // 订单审核直接流转到客服
                order.setAuditor(kefuVo.getId());
                order.setAuditDept(AuditDeptEnum.SERVICE_DEPT.getValue());
                order.setAuditStatus(OrderAuditStateEnum.AGENT_AUDIT_SUCCESS.getValue());
                order.setOrderStatus(OrderStateEnum.HAS_PAY.getValue());
                // 代理获利计算
                orderAgentList.addAll(profitManager.calcProfit(order, null, rebateRule));
                // 校验是否更新收货地址
                if (StrUtil.isNotEmpty(dto.getContactUser())) {
                    if (StrUtil.isEmpty(dto.getContactPhone())
                            || StrUtil.isEmpty(dto.getProvince())
                            || StrUtil.isEmpty(dto.getCity())
                            || StrUtil.isEmpty(dto.getRegion())
                            || StrUtil.isEmpty(dto.getAddrDetail())) {
                        throw new BusinessException("请完善收货人及收货地址信息");
                    }
                    OrderExpress byOrderId = orderExpressService.findByOrderId(order.getId());
                    if (!byOrderId.getContactUser().equals(dto.getContactUser().trim())
                            || !byOrderId.getContactPhone().equals(dto.getContactPhone())
                            || !byOrderId.getProvince().equals(dto.getProvince())
                            || !byOrderId.getCity().equals(dto.getCity())
                            || !byOrderId.getRegion().equals(dto.getRegion())
                            || !byOrderId.getAddrDetail().equals(dto.getAddrDetail())) {
                        byOrderId.setContactUser(dto.getContactUser());
                        byOrderId.setContactPhone(dto.getContactPhone());
                        byOrderId.setProvince(dto.getProvince());
                        byOrderId.setCity(dto.getCity());
                        byOrderId.setRegion(dto.getRegion());
                        byOrderId.setAddrDetail(dto.getAddrDetail());
                        orderExpressService.updateById(byOrderId);
                    }
                }
                orderList.add(order);
            }

        }
        orderService.executeSeckillOrderImport(orderList, orderAgentList);
        return ResultUtil.success();
    }


    @PostMapping("actOrderSettleNotify")
    public Result actOrderSettleNotify(@RequestBody List<Long> orderIds) {


        List<Order> orders = (List<Order>) orderService.listByIds(orderIds);
        for (Order order : orders) {
            order.setSettleState(SettleStateEnum.SETTLED.getValue());
        }
        orderService.updateBatchById(orders);
        return ResultUtil.success();
    }


    @GetMapping("/getAllAgentIdOfToAuditOder")
    public Result getAllAgentIdOfToAuditOder() {
        //orderReportService.synchronousData(someday);

        return ResultUtil.success("同步成功");
    }


    @GetMapping("/autoConfirmOrder")
    public Result autoConfirmOrder() {
        orderService.autoConfirmOrder();
        return ResultUtil.success("success");
    }


    @PostMapping("/cancelOrder")
    public Result cancelOrder(long orderId) {
        orderService.cancelOrder(orderId);
        return ResultUtil.success("success");
    }

    @GetMapping("/checkHasAuditOrder")
    public Result checkHasAuditOrder(long agentId) {
        AgentOrderQuery query = new AgentOrderQuery();
        query.setIsPay(WhetherEnum.YES);
        query.setIsDel(WhetherEnum.NO);
        query.setAuditDept(AuditDeptEnum.AGENT);
        List<Integer> states = Lists.newArrayList();
        states.add(OrderStateEnum.HAS_PAY.getValue());
        states.add(OrderStateEnum.AUDITING.getValue());
        query.setOrderStates(states);
        query.setAgentIdForQueryAll(agentId);
        IPage<FrontAgentOrderVo> record = agentOrderService.selectAgentOrderListOfPage(new Page(1, 10), query, agentId);
        if (CollUtil.isNotEmpty(record.getRecords())) {
            return ResultUtil.success(WhetherEnum.YES.getValue());
        }
        return ResultUtil.success(WhetherEnum.NO.getValue());
    }

    @GetMapping("/updateTag")
    public Result updateTag(Long orderId, Integer sysTag, Integer appTag) {
        if (orderId == null) {
            return ResultUtil.error();
        }
        orderService.updateTag(orderId, sysTag, appTag);
        return ResultUtil.success();
    }

    @GetMapping("/getAgentRuleData")
    public Result getAgentRuleData(Long agentId, String startTime, String endTime) {
        return ResultUtil.success(orderService.getAgentRuleData(agentId, startTime, endTime));
    }


    @GetMapping("/checkMemberOrderByMemberId")
    public Result checkMemberOrderByMemberId(Long memberId) {
        QueryWrapper<Order> wrapper = new QueryWrapper<Order>();
        wrapper.eq("buyer_id", memberId);
        wrapper.eq("order_from", OrderFromEnum.MEMBER.getValue());
        List<Order> list = orderService.list(wrapper);
        if (CollUtil.isNotEmpty(list)) {
            return ResultUtil.success(WhetherEnum.YES.getValue());
        }
        return ResultUtil.success(WhetherEnum.NO.getValue());
    }
}
